<?php
//declare (strict_types=1);
/**
 * @Description:
 * @Author: Chern
 * @Date: 2023/7/11
 * @Time: 10:52
 */

namespace app\service;
use app\model\SystemFieldPower;
use app\model\SystemFieldRandPower;
use app\model\SystemMenu;
use app\model\UserOrganization;
use app\stateData;
use Exception;
use think\facade\Db;
use think\helper\Str;

class System
{
    /**
     * 接收数据进行tree处理
     * @param $data
     * @param int $pid
     * @return array
     */
    public function menuTreeList($data, int $pid=0,$level=0):array
    {
        $result = array();
        $level++;
//        if ($level > 4){
//            return $result;
//        }
        foreach ($data as  $datum) {

            if ($datum['parent_id'] == $pid){

                if (!empty($this->menuTreeList($data,$datum['id'],$level))){
                    $datum['childs'] = $this->menuTreeList($data,$datum['id'],$level);
                }
                $result[] = $datum;
            }
        }

        return $result;
    }

    /**
     * 寻找某一级组织架构tree  保留父级信息
     * @param $data
     * @param int $pid
     * @return array
     */
    public function OrgParentTreeList($data, int $pid=0):array
    {
        if (!$data){
            return [];
        }
        $result = [];
        foreach ($data as $k => $datum) {
            if ($k == 0){
                continue;
            }
            if ($datum['parent_id'] == $pid){

                if (!empty($this->menuTreeList($data,$datum['id']))){
                    $datum['childs'] = $this->menuTreeList($data,$datum['id']);
                }
                $data[0]['childs'][] = $datum;
            }
        }
        $result[] = $data[0];
        return $result;
    }


    /**
     * 接收数据进行tree处理 删除checked false
     * @param $data
     * @param int $pid
     * @param $level
     * @return array
     */
    public function menuTreeDelFalse($data, int $pid=0,$level=0):array
    {
        $result = array();
        foreach ($data as $k => &$datum) {

            //如果checked false 删除
            if (!$datum['checked']){
                unset($data[$k]);
                continue;
            }

            if ($datum['parent_id'] == $pid){

                if (!empty($this->menuTreeDelFalse($data,$datum['id'],$level))){
                    $datum['childs'] = $this->menuTreeDelFalse($data,$datum['id'],$level);
                }
                $result[] = $datum;
            }
        }
        return $result;
    }


    /**
     * 根据条件进行tree
     */
    public function menuWhereTerr($data,$model)
    {
        $arr = [];
        $datas = $this->array_unique_key($data,'business_type'); //一级
        for ($i = 0, $iMax = count ($datas); $i < $iMax; $i++) {
            foreach ($data as $j => $jValue) {

                if ($datas[$i] == $jValue['business_type']){
                    $arr[$i]['business_name'] = $data[$j]['business_type'];
                    $arr[$i]['id'] = $data[$j]['id'];

                    if (isset($arr[$i]['childs'])){
                        if (!in_array ($jValue['business_category'],$arr[$i]['childs']) ){
                            $arr[$i]['childs'][] = $jValue;
                            for ($k = 0, $kMax = count ($arr[$i]['childs']); $k < $kMax; $k++) {
                                if (!empty($arr[$i]['childs'][$k]['business_category'])){
                                    $arr[$i]['childs'][$k]['childs'] = $model->getWhereBusinessCategoryModel($arr[$i]['childs'][$k]['business_category']);
                                }
                            }
                        }
                    }else{
                        $arr[$i]['childs'][] = $jValue;
                        for ($k = 0, $kMax = count ($arr[$i]['childs']); $k < $kMax; $k++) {
                            if (!empty($arr[$i]['childs'][$k]['business_category'])){
                                $arr[$i]['childs'][$k]['childs'] = $model->getWhereBusinessCategoryModel($arr[$i]['childs'][$k]['business_category']);
                            }
                        }
                    }

                }
            }
        }
        return $arr;
    }

    /**
     * 重复方法，business_name改为title
     */
    public function menuTitleTerr($data,$model): array
    {
        //根据business_name查询子集
        foreach ($data as &$datum) {

            $datum['childs'] = $model->getBNameCategoryModel($datum['title']);
        }
        return $data;
    }


    //一级业务分类去重
    public function array_unique_key($arr, $key): array
    {

        $tmp_arr=array();
        foreach($arr as $k => $v){
            if(in_array($v[$key],$tmp_arr)){   //判断是否重复
                unset($arr[$k]);   //重复则删除
            }else{

                $tmp_arr[]=$v[$key];  //将值存储在临时数组中
            }
        }
        return $tmp_arr;
    }


    /**
     * @param  $str
     * @return array|string
     */
    public function analysisId($str)
    {
        $result = [];
        if (empty($str)){
            return $result;
        }

        if (Str::contains($str, ',')){

            $result = explode(",",$str);
        }else{
            $result = (array)$str;
        }

        return $result;
    }

    /**
     * @param $arr
     * @param $array
     * @return array
     */
    public function arrAssignmentId($arr,$array): array
    {
        $count = count($arr);

        $result = [];

        for ($i = 0; $i < $count; $i++) {

            $result[$i]['roles_id'] = $arr[$i];
            $result[$i] += $array;
        }
        return $result;
    }

    /**
     * @param $arr //权限池
     * @param $arr2 //已经设置的权限
     * 匹配该权限是否已经设置
     * 存在check true
     */
    public function powerPoint($arr,$arr2,$arrId = 'id',$arr2Id = 'id',$del=false): array
    {
        $clue = new Clue();
        $systemFieldModel = new SystemFieldRandPower();
        foreach ($arr as $i => &$iValue) {
            //如果select  查询该字段对应option
            if (!empty($iValue['option']) || !empty($iValue['option_data'])){
                $arr[$i]['value'] = $clue->getOption ($iValue);
            }else{
                $arr[$i]['value'] = '';
            }

            //系统字段权限
            if(isset($iValue['attribute'])){
                if($iValue['attribute'] === '系统字段'){
                    //如果用户权限不包括系统字段 查询字段权限库是否存在该字段权限
                    $ids = $systemFieldModel->getFieldIdData($iValue['id']);
                    if (!$ids){
                        $iValue['checked'] =true;
                        continue;
                    }
//                    //先查询字段权限库是否有设置该字段可见范围权限
//                    $ids = $systemFieldModel->getFieldIdData($iValue['id']);
//                    if (!$ids){
//                        $iValue['checked'] =true;
//                        continue;
//                    }
//                    //不为空判断当前uid是否存在权限范围内 在 true
                }
            }


            if (!empty($arr2)){

                foreach ($arr2 as $jValue) {

                    if (empty($jValue)){
//                        unset($arr[$i]);
                        $arr[$i]['checked'] = false;
                        break;
                    }

                   if (!is_array ($jValue)){

                       if ($iValue[$arrId] == $jValue){

                           $arr[$i]['checked'] = true;
                           break;
                       }
//                       unset($arr[$i]);
                       $arr[$i]['checked'] = false;

                   }else{
                       if ($iValue[$arrId] == $jValue[$arr2Id]){

                           $arr[$i]['checked'] = true;
                           break;
                       }

                       $arr[$i]['checked'] = false;
//                       unset($arr[$i]);
                   }
                }
            }else{

                $arr[$i]['checked'] = false;
//                unset($arr[$i]);
            }
            if ($del && !$arr[$i]['checked']) {
                unset($arr[$i]);
            }
        }
        return $arr;
    }


    /**
     * 系统字段拼接模板id
     * @param $data
     * @param $fid
     * @return mixed
     */
    public function systemFieldMontage($data,$fid)
    {
        $cou = count($data);

        for ($i = 0; $i < $cou; $i++) $data[$i]['fid']=$fid;

        return $data;
    }

    /**
     * 自定义字段添加
     * @param $id
     * @param $account_type
     * @param $power_type
     * @param $fid
     * @param $param
     * @throws \Exception
     */
    public function addFieldPower(
        $id, $account_type, $power_type, $fid, $param
    ){

        $systemFieldPower = new SystemFieldPower();

        $systemFieldPower->delWhereFieldPowerModel($id,$account_type,$power_type,$fid);//先删除再批量添加

        $data = $this->analysisId($param);//id字符串转数组

        $assignmentData = $this->arrAssignmentId($data,[
            'account_type'=>$account_type,
            'power_type'=>$power_type,
            'field_id'=>$id,
            'from_id'=>$fid,

        ]);

        return $systemFieldPower->addFieldPowerModel($assignmentData);
    }

    /**
     * 如果有角色權限传入
     * @param $param
     * @return void
     * @throws \Exception
     */
    public function isPostPower($param)
    {

        if (isset($param['position'])) {
            $data = $this->addFieldPower(
                $param['id'],
                stateData::$_power_from_identifying['position'],
                stateData::$_power_type['field'],
                $param['fid'],
                $param['position']
            );
        }
        //如果有角色架构权限传入
        if (isset($param['organization'])) {
           $data = $this->addFieldPower(
                $param['id'],
                stateData::$_power_from_identifying['organization'],
                stateData::$_power_type['field'],
                $param['fid'],
                $param['organization']
            );

        }
        //如果有个人权限传入
        if (isset($param['people'])) {
           $data = $this->addFieldPower(
                $param['id'],
                stateData::$_power_from_identifying['people'],
                stateData::$_power_type['field'],
                $param['fid'],
                $param['people']
            );
        }
    }


    /**
     * 获取组织架构 增加部门人员列表
     */
    public function getOrgTypeUserList($data,$pid=0): array
    {
        $user = new \app\model\User();

        $result = [];

        foreach ($data as $datum) {
            if ($datum['parent_id'] == $pid){

                if (!empty($this->getOrgTypeUserList($data,$datum['id']))){
                    $datum['childs'] = $this->getOrgTypeUserList($data,$datum['id']);
                }
                $result[] = $datum;
            }

            if (!isset($datum['childs'])){
                //获取部门人员
                $datum['childs'] = $user->getIdTitle($datum['id']);
            }
        }

        return $result;
    }


    /**
     * 区域多级分类
     */
    public function getAreaTree($data,$pid=0)
    {
        $redis = new RedisService();
        $reData = $redis->getAreaData();
        if ($reData){
            return $reData;
        }
        $result = $this->getAreaData($data,$pid);
        $redis->setAreaData($result);
        return $result;
    }

    public function getAreaData($data,$pid)
    {
        $result = [];
        foreach ($data as $datum) {

            if ($datum['parent_id'] == $pid){
                if (!empty($this->getAreaData($data,$datum['code_id']))){
                    $datum['childs'] = $this->getAreaData($data,$datum['code_id']);
                }
                $result[] = $datum;
            }
        }
        return $result;
    }


    /**
     * 获取省市区层级关系
     * @param $code_id
     * @param array $arr
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSuperAreaArray($code_id, array $arr = [])
    {
        $info = Db::table('system_china')->where('code_id', $code_id)->field('parent_id')->find();

        if ($info && $info['parent_id']) {
            array_unshift($arr, $info['parent_id']);
            return $this->getSuperAreaArray($info['parent_id'], $arr);
        }
        return $arr;
    }

    /**
     * 查询组织架构延伸子集
     */
    public function getOrgIdStr($id,$data,$bool=true)
    {
        $str = '';
        if ($bool){
            $str = $id.',';
        }
        foreach ($data as $datum) {

            if ($datum['parent_id'] == $id){

                if (!empty($this->getOrgIdStr ($datum['id'],$data))){
                    $str .= $this->getOrgIdStr ($datum['id'],$data);
                }
            }
        }
        return $str;
    }

    /**
     * 通过子集寻找父级所有id
     * @param $id
     * @param $data
     * @param bool $bool
     * @return string
     */
    public function getParentIdStr($id, $data, bool $bool=true)
    {
        $str = '';
        if ($bool){
            if ($id !== 0){
                $str = $id.',';
            }
        }
        foreach ($data as $datum) {
            if ($datum['id'] == $id){

                if ($this->getParentIdStr ($datum['parent_id'],$data)){
                    $str .= $this->getParentIdStr ($datum['parent_id'],$data);
                }
            }
        }
        return $str;
    }



    /**
     * 菜单别名查询父级
     * @param $str //菜单权限字符串
     */
    public function getMenuParentId($str)
    {
        $menuModel = new SystemMenu();

        $aliasArr = explode (',',$str);

        foreach ($aliasArr as $item) {
            $parentAlias = $menuModel->getParentAliasModel($item); //找一级
            if ($parentAlias){
                if (!array_search ($parentAlias, $aliasArr, true)){
                    $aliasArr[] = $parentAlias;
                }
                $palias = $menuModel->getParentAliasModel($parentAlias); //第二级
                if ($palias){
                    if (!array_search ($palias, $aliasArr, true)){
                        $aliasArr[] = $palias;
                    }
                    $palia = $menuModel->getParentAliasModel($palias); //第三级
                    if ($palia){
                        if (!array_search ($palia, $aliasArr, true)){
                            $aliasArr[] = $palia;
                        }
                        $pal = $menuModel->getParentAliasModel($palia); //第四级

                        if ($pal){
                            if (!array_search ($pal, $aliasArr, true)){
                                $aliasArr[] = $pal;
                            }
                        }
                    }
                }
            }
        }
        return implode (',', $aliasArr);
    }

    /**
     * 获取当前部门所在的总公司
     */
    public function getOrgZgsId($orgId)
    {
        static $id;
        $id = $orgId;
        $orgModel = new UserOrganization();

        $orgData = $orgModel->getUserDepartmentInfoModel($id);
        if (!$orgData){
            return '';
        }
        if ($orgData['parent_id'] === 0){
            return $id;
        }
        $this->getOrgZgsId ($orgData['parent_id']);
        return $id;
    }

    /**
     * 获取当前部门所在分公司
     */
    public function getOrgFgsId($orgId)
    {
        static $id;

        $id .= $orgId.',';
        $orgModel = new UserOrganization();
        $arr = explode (',',$id);

        $orgData = $orgModel->getUserDepartmentInfoModel($arr[count ($arr)-2]);

        if ($orgData['parent_id'] === 0){
            return $id;
        }

        $this->getOrgFgsId ($orgData['parent_id']);
        $array = explode (',',$id);
        return $array[count($array)-3];
    }

    /**
     * 通过部门id 获取完整部门文本路径
     */
    public function getOrgStrName($orgId)
    {
        $orgModel = new UserOrganization();
        if (!$orgId){
            return '';
        }

        $orgStr = rtrim ($this->getParentIdStr($orgId,$orgModel->getStructure ()),',');

        $arr = explode (',',$orgStr);

        $nameStr = '';
        for ($i = count($arr)-1; $i >= 0 ; $i--) {
            $nameStr .= $orgModel->getStructureName ($arr[$i]).'/';
        }

        return rtrim ($nameStr,'/');
    }

    /**
     * 判断身份证号码是否正确
     * @param $idNumber
     * @return bool
     */
    function isValidIDCardNumber($idNumber) {
        $idNumber = strtoupper($idNumber); // 将输入的身份证号码转换为大写字母
        $regex = '/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])\d{3}(\d|X|x)$/'; // 身份证号码的正则表达式

        if (!preg_match($regex, $idNumber)) {
            return false; // 身份证号码格式不正确
        }

        // 验证最后一位校验码
        $weight = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
        $checkCode = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
        $sum = 0;
        for ($i = 0; $i < 17; $i++) {
            $sum += (int)$idNumber{$i} * $weight[$i];
        }
        $mod = $sum % 11;
        $checkBit = $checkCode[$mod];

//        if ($idNumber{17} !== $checkBit) {
//            return false; // 最后一位校验码不匹配
//        }

        return true; // 身份证号码有效
    }
}